package com.d3works.apps.account.service.invoice.generator.batch;

import com.d3works.apps.account.db.Invoice;
import com.d3works.apps.account.exception.AccountExceptionMessage;
import com.d3works.apps.account.service.invoice.InvoiceService;
import com.d3works.apps.base.exceptions.BaseExceptionMessage;
import com.d3works.db.JPA;
import com.d3works.exception.D3worksException;
import com.d3works.exception.db.repo.ExceptionOriginRepository;
import com.d3works.exception.service.TraceBackService;
import com.d3works.i18n.I18n;
import com.google.inject.Inject;
import java.lang.invoke.MethodHandles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BatchVentilation extends BatchWkf {

  static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

  @Inject
  public BatchVentilation(InvoiceService invoiceService) {

    super(invoiceService);
  }

  @Override
  protected void process() {

    for (Invoice invoice : invoices(batch.getInvoiceBatch(), true)) {

      try {

        invoiceService.ventilate(invoiceRepo.find(invoice.getId()));
        updateInvoice(invoiceRepo.find(invoice.getId()));

      } catch (D3worksException e) {

        TraceBackService.trace(
            new D3worksException(
                e, e.getCategory(), I18n.get("Invoice") + " %s", invoice.getInvoiceId()),
            ExceptionOriginRepository.INVOICE_ORIGIN,
            batch.getId());
        incrementAnomaly();

      } catch (Exception e) {

        TraceBackService.trace(
            new Exception(String.format(I18n.get("Invoice") + " %s", invoice.getInvoiceId()), e),
            ExceptionOriginRepository.INVOICE_ORIGIN,
            batch.getId());
        incrementAnomaly();

      } finally {

        JPA.clear();
      }
    }
  }

  @Override
  protected void stop() {

    String comment = I18n.get(AccountExceptionMessage.BATCH_VENTILATION_1) + "\n";
    comment +=
        String.format(
            "\t* %s " + I18n.get(AccountExceptionMessage.BATCH_VENTILATION_2) + "\n",
            batch.getDone());
    comment +=
        String.format(
            "\t" + I18n.get(BaseExceptionMessage.ALARM_ENGINE_BATCH_4), batch.getAnomaly());

    super.stop();
    addComment(comment);
  }
}
